package com.ckjava.aop;

import com.ckjava.xutils.ArrayUtils;
import com.ckjava.xutils.CollectionUtils;
import com.ckjava.xutils.ExceptionUtils;
import com.ckjava.xutils.JsonUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(2)
public class AutoLogAop extends AopBase {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Around("autoLog()")
    public Object handleLog(ProceedingJoinPoint joinPoint) {
        // 记录下请求内容
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] methodArgs = joinPoint.getArgs();

        // 目标方法的处理
        try {
            long begin = System.currentTimeMillis();
            Object returnObj = joinPoint.proceed(methodArgs);
            long consumeTime = System.currentTimeMillis() - begin;

            logger.info(JsonUtils.toJSONString(CollectionUtils.asHashMap(
                    ArrayUtils.toArray("classMethod", "methodArgs", "return", "consumeTime"),
                    ArrayUtils.toArray(classMethod, methodArgs, returnObj, consumeTime + " ms"))));

            return returnObj;
        } catch (Throwable e) {
            logger.error(JsonUtils.toJSONString(CollectionUtils.asHashMap(
                    ArrayUtils.toArray("classMethod", "methodArgs", "exception"),
                    ArrayUtils.toArray(classMethod, methodArgs, ExceptionUtils.getExceptionMsg(e)))));

            return null;
        }
    }

}
